package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.core.aspect.WebLog;
import com.jumi.microservice.common.utils.HttpRquestUtil;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.NumberConstant;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.controller.base.BaseController;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.service.RelationTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 关联版式表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-27
 */
@RestController
@Api(tags = "关联版式表 相关接口")
@RequestMapping("/commodity/relation/template")
public class RelationTemplateController extends BaseController {

    @Autowired
    private RelationTemplateService relationTemplateService;


    @ApiOperation(value = "新增数据", notes = "新增一条关联版式表数据")
    @PostMapping("/add")
    @WebLog(description = "新增商品关联版式")
    public ResponseResult add(@Validated @RequestBody RelationTemplateVO relationTemplate, HttpServletRequest request) {
        RelationTemplateDTO dto = vo2Dto(relationTemplate);
        dto.setCreater(HttpRquestUtil.getUserName(request));
        dto.setModifier(HttpRquestUtil.getUserName(request));
        relationTemplateService.saveRelationTemplate(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "(批量)删除数据", notes = "删除指定ID关联版式表数据")
    @ApiImplicitParam(name = "ids", value = "ids")
    @DeleteMapping("/delete")
    @WebLog(description = "删除商品关联版式")
    public ResponseResult delete(@RequestParam String ids, HttpServletRequest request) {
        String uname = HttpRquestUtil.getUserName(request);
        relationTemplateService.delete(ids, uname);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID关联版式表数据")
    @PutMapping("/update")
    @WebLog(description = "更新商品关联版式")
    public ResponseResult update(@Validated @RequestBody RelationTemplateVO relationTemplate, HttpServletRequest request) {
        RelationTemplateDTO dto = vo2Dto(relationTemplate);
        dto.setCreater(HttpRquestUtil.getUserName(request));
        dto.setModifier(HttpRquestUtil.getUserName(request));
        relationTemplateService.updateRt(dto);
        return ResultGenerator.genSuccessResult(relationTemplate);
    }


    @ApiOperation(value = "查询数据", notes = "获取指定ID关联版式表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<RelationTemplateVO> detail(@RequestParam Long id) {
        RelationTemplateDTO dto = relationTemplateService.selectById(id);
        return ResultGenerator.genSuccessResult(dto2Vo(dto));
    }


    @ApiOperation(value = "查询分页", notes = "获取关联版式表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse<List<RelationTemplateVO>> list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            RelationTemplateVO relationTemplate) {
        LambdaQueryWrapper<RelationTemplateDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(relationTemplate.getTemplatePosition()!=null, RelationTemplateDO::getTemplatePosition,relationTemplate.getTemplatePosition());
        wrapper.like(StringUtils.isNotEmpty(relationTemplate.getTemplateName()), RelationTemplateDO::getTemplateName,relationTemplate.getTemplateName());
        wrapper.eq(RelationTemplateDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.eq(relationTemplate.getStatus()!=null,RelationTemplateDO::getStatus,relationTemplate.getStatus());
        wrapper.orderByDesc(RelationTemplateDO::getId, RelationTemplateDO::getUpdateTime);
        IPage<RelationTemplateDO> pageInfo = relationTemplateService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()),pageInfo.getTotal());
    }

    @ApiOperation(value = "启用/禁用商品关联版式", notes = "启用/禁用商品关联版式")
    @PutMapping("/enableStatus")
    @WebLog(description = "启用/禁用商品关联版式")
    public ResponseResult enableStatus(@RequestParam Long id, Integer status, HttpServletRequest request) {
        String uname = HttpRquestUtil.getUserName(request);
        relationTemplateService.enableStatus(id, status, uname);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "添加商品-顶底部版式", notes = "添加商品-顶底部版式")
    @GetMapping("/listDrop")
    public ResponseResult listDrop() {
        LambdaQueryWrapper<RelationTemplateDO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RelationTemplateDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.eq(RelationTemplateDO::getStatus, StatusEnum.STATUS_YES.getCode());
        wrapper.orderByDesc(RelationTemplateDO::getId, RelationTemplateDO::getUpdateTime);
        List<RelationTemplateDO> list = relationTemplateService.list(wrapper);
        List<RelationTempletDropVO> topList = new ArrayList<>();
        List<RelationTempletDropVO> bottomList = new ArrayList<>();
        list.stream().forEach(po->{
            RelationTempletDropVO vo = new RelationTempletDropVO();
            vo.setId(po.getId());
            vo.setTemplateName(po.getTemplateName());
            if(NumberConstant.NUMBER_ONE.intValue()==po.getTemplatePosition()){
                topList.add(vo);
            }else{
                bottomList.add(vo);
            }
        });
        return ResultGenerator.genSuccessResult(new RelationTempletsDropVO(topList,bottomList));
    }

    /**
     * vo->dto
     * @param vo
     * @return
     */
    private RelationTemplateDTO vo2Dto(RelationTemplateVO vo){
        RelationTemplateDTO dto = null;
        try {
            dto = vo.clone(RelationTemplateDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }

    /**
     * dto->vo
     * @param dto
     * @return
     */
    private RelationTemplateVO dto2Vo(RelationTemplateDTO dto){
        RelationTemplateVO vo = null;
        try {
            vo = dto.clone(RelationTemplateVO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return vo;
    }

    private List<RelationTemplateVO> pos2Vos(List<RelationTemplateDO> list){
        return list.stream().map(p->{
            RelationTemplateVO vo = null;
            try {
                vo = p.clone(RelationTemplateVO.class);
            }catch (Exception e){
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
    }

}
